package com.wxl.common.wiget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

public class NoScrollRecyclerView extends RecyclerView {

    public NoScrollRecyclerView(@NonNull Context context) {
        super(context);
    }

    public NoScrollRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public NoScrollRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        if(!canScroll){
            return true;
        }
        return super.onTouchEvent(e);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        if(!canScroll){
            return true;
        }
        return super.onInterceptTouchEvent(e);
    }

    private boolean canScroll = false;

    public void setCanScroll(boolean canScroll) {
        this.canScroll = canScroll;
        setFocusable(canScroll);
        this.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 如果自动滑动到最后一个位置，则此处状态为SCROLL_STATE_IDLE
                    AutoScrollLayoutManager lm = (AutoScrollLayoutManager) recyclerView.getLayoutManager();

                    int position = lm.findLastCompletelyVisibleItemPosition();
                    int count = lm.getItemCount();
                    Adapter adapter = recyclerView.getAdapter();
                    if(position == count-1 && adapter != null){
                        lm.scrollToPosition(0);
                        NoScrollRecyclerView.this.smoothScrollToPosition(adapter.getItemCount());
                    }
                }
            }
        });
    }
}
